package net.lovesrc.allin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zhouzhou.fastjava.query.*;
import com.zhouzhou.fastjava.query.dialect.MySQLDialect;
import net.lovesrc.allin.BaseBean;
import net.lovesrc.allin.Cnsts;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

public abstract class BaseController extends BaseBean {

    @Autowired
    private ResourcePatternResolver resourcePatternResolver;

    @Autowired
    private DataSource dataSource;

    @Autowired
    protected JdbcTemplate jdbcTemplate;

    protected QueryResult query(String name, QueryArgs args) throws Exception {

        JSONConfigBuilder configBuilder = new JSONConfigBuilder(resourcePatternResolver, this.getClass().getResourceAsStream("/query.json"));
        QueryConfiguration configuration = configBuilder.parse();
        configuration.setShowSql(true);
        configuration.setDebug(true);
        configuration.setDialect(new MySQLDialect());
        configuration.setDataSource(dataSource);
        QueryExecutor executor = configuration.newExecutor();
        args.getStaticFilters().put("userId", getCurrentUserId());
        return executor.execute(name, args);
    }

    protected String getCurrentUserId() {

        return (String) getSession().getAttribute(Cnsts.SESSION_KEY_USER_ID);
    }

    protected String[] toStringIds(String ids) {
        return StringUtils.split(ids, ",");
    }

    protected Long[] toLongIds(String ids) {
        String[] strIds = StringUtils.split(ids, ",");
        List<Long> result = Lists.newArrayList();
        for (String strId : strIds) {
            result.add(Long.valueOf(strId));
        }
        return result.toArray(new Long[result.size()]);
    }

    protected HttpSession getSession() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest().getSession();
    }

    protected JSONObject toJsonObject(Map<String, String> params) {
        return JSON.parseObject(JSON.toJSONString(params));
    }

}
